package space.panker916.controller.advice;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import space.panker916.pojo.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice(annotations = {Controller.class, ControllerAdvice.class})
@ResponseBody
public class ProjectExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ProjectExceptionAdvice.class);

    @ExceptionHandler
    public R handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.error("服务器发生异常：" + e.getMessage());
        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
            logger.error(stackTraceElement.toString());
        }

        // 判断是 普通请求 还是 异步请求
        String xReq = request.getHeader("x-requested-with");
        if (StringUtils.isNotBlank(xReq) && "XMLHttpRequest".equalsIgnoreCase(xReq)) {
            // 是ajax异步请求
            return new R(1, "服务器异常！");
        } else response.sendRedirect(request.getContextPath() + "/error");

        return null;
    }
}
